package com.cqhfan.chatroom.handler;

import cn.hutool.json.JSONUtil;
import com.cqhfan.chatroom.domain.dto.WebSocketMessageDTO;
import com.cqhfan.chatroom.enums.ChatType;
import com.cqhfan.chatroom.enums.MessageType;
import com.cqhfan.common.autoconfigure.mq.RabbitMqHelper;
import com.cqhfan.common.constants.MqConstants;
import com.cqhfan.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.time.LocalDateTime;


/**
 * @author 眭传洪
 * @create 2024-11-19 20:00
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ImMessageHandler extends TextWebSocketHandler {

    private final RabbitMqHelper mqHelper;

    @Value("${server.port}")
    private String port;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 这里其实就打个日志就可以了 因为集群下发消息不依靠这个
        log.info("sessionId = {} 连接到websocket服务", session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("sessionId = {} 断开websocket服务", session.getId());
    }

    @Override
    protected void handleTextMessage(@NotNull WebSocketSession session, TextMessage message) throws Exception {
        // 获取消息
        String payload = message.getPayload();
        WebSocketMessageDTO chatMessage = JSONUtil.toBean(payload, WebSocketMessageDTO.class);
        if (chatMessage == null) {
            return;
        }
        log.info("{}", chatMessage);
        // 根据消息类型不同分别处理
        MessageType messageType = MessageType.fromValue(chatMessage.getMessageType());
        switch (messageType) {
            case CONNECTION -> {
                // 连接消息
                Long userId = chatMessage.getSenderId();
                UserConnectionSession.addUserIdSessionRelation(userId, session);
            }
            case EXIT -> {
                Long userId = chatMessage.getSenderId();
                UserConnectionSession.removeUserIdSessionRelation(userId);
            }
            case CREATE_GROUP -> {
                // 通知所有群里的人 前端创建聊天项
                setChatTime(chatMessage);
                String msg = JSONUtil.toJsonStr(chatMessage);
                mqHelper.sendMessage(
                        MqConstants.ExChange.CHAT_CREATE_GROUP_EXCHANGE,
                        null,
                        msg
                );
            }
            case TEXT -> {
                setChatTime(chatMessage);
                String msg = JSONUtil.toJsonStr(chatMessage);
                // 发送消息
                mqHelper.sendMessage(
                        MqConstants.ExChange.CHAT_SEND_EXCHANGE,
                        null,
                        msg

                );

                // 异步保存消息
                mqHelper.sendMessage(
                        MqConstants.ExChange.CHAT_EXCHANGE,
                        MqConstants.key.SAVE_TO_DB + "." + port,
                        msg
                );
            }
        }
    }

    private void setChatTime(WebSocketMessageDTO msg) {
        LocalDateTime now = LocalDateTime.now();
        String chatTime = DateUtils.getDefaultDateTimeFormatter().format(now);
        msg.setChatTime(chatTime);
    }
}
